//
//  WMHTMLView.m
//  ChannelSoftWeMarketing
//
//  Created by channelsoftios on 17/8/3.
//  Copyright © 2017年 channelsoftios. All rights reserved.
//

#import "WMHTMLView.h"
#import "HomeNetManager.h"
@interface WMHTMLView ()<WKUIDelegate,WKNavigationDelegate>

@property (strong, nonatomic) UIProgressView *progressView;

@property (nonatomic, copy) NSString *coinAmountStr;

@property (nonatomic, assign) BOOL isFinishBool;

@end

@implementation WMHTMLView

- (void)dealloc {
    
    if (_showProgressView) {
        [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
    }
    
    _webView.navigationDelegate = nil;
    _webView.UIDelegate = nil;
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.showProgressView = YES;
        [self webViewInit];
    }
    return self;
}

//获取可用CT
- (void)getBalanceCoinInfo {
    [HomeNetManager getMemberAsset:[YLUserInfo shareUserInfo].ID CompleteHandle:^(id resPonseObj, int code) {
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                
                self.coinAmountStr = [NSString stringWithFormat:@"%@",resPonseObj[@"data"][@"amount"]];
                
                NSString *jsStr = [NSString stringWithFormat:@"ctNumber('%@')",self.coinAmountStr];
                [_webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                    NSLog(@"%@",error);
                }];
            }
        }
        else {
            [self makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

//开始游戏
- (void)setStartGame:(NSString *)type{
    
    if (self.isFinishBool == NO) { //断点是否加载完成
        return;
    }
    [HomeNetManager startGame:[YLUserInfo shareUserInfo].ID gameId:self.gameIdStr CompleteHandle:^(id resPonseObj, int code) {
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                
                //通知H5开始游戏
                if ([type isEqualToString:@"0"]) {
                    NSString *jsStr = @"startOn(true)";
                    [_webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                        NSLog(@"%@",error);
                    }];
                }
                else{
                    NSString *jsStr = @"again(true)";
                    [_webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable response, NSError * _Nullable error) {
                        NSLog(@"%@",error);
                    }];
                }
                
                //获取CT余额
                [self getBalanceCoinInfo];
               
            }
            else{
                
                [self makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            
            [self makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

//游戏结束上传分数
- (void)setUpScore:(NSString *)scoreStr{
    [HomeNetManager updateScore:[YLUserInfo shareUserInfo].ID gameId:self.gameIdStr score:scoreStr CompleteHandle:^(id resPonseObj, int code) {
        if (code) {
            if ([resPonseObj[@"code"] integerValue] == 0) {
                
            }
            else{
                [self makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [self makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

//加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    [self getBalanceCoinInfo];
    self.isFinishBool = YES;

}

- (void)setWebViewRect:(CGRect)webViewRect {
    _webViewRect = webViewRect;
    
    _webView.frame = webViewRect;
}

//接收H5数据
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    if (message == nil) {
        completionHandler();
        return;
    }
    
    NSData *jsonData = [message dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *bodyDic = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"%@",bodyDic);
    
    if (![[YLUserInfo shareUserInfo].ID isEqualToString:[NSString stringWithFormat:@"%@",bodyDic[@"userid"]]] || ![self.gameIdStr isEqualToString:[NSString stringWithFormat:@"%@",bodyDic[@"gameid"]]]) {
        
        [self makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        
        completionHandler();
        return;
    }
    
    NSString *scoreStr = [NSString stringWithFormat:@"%@",bodyDic[@"score"]];
    if ([scoreStr isEqualToString:@"0"]) {
        //开始
        if ([[NSString stringWithFormat:@"%@",bodyDic[@"restart"]] isEqualToString:@"1"]) {
            //第一次开始
            [self setStartGame:@"0"];

        }
        else{
            //重新开始
            [self setStartGame:@"1"];
        }
    }
    else{
        //结束
        if ([scoreStr isEqualToString:@"no"]) {
            scoreStr = @"0";
        }
        [self setUpScore:scoreStr];
    }
    
    completionHandler();
}

- (void)webViewInit {
    
    if (!_webView) {
        _webView = [[WKWebView alloc] init];
        _webView.UIDelegate = self;
        _webView.navigationDelegate = self;
        
        if ([self.isBouncesStr isEqualToString:@"1"]) {
            _webView.scrollView.bounces = NO;
        }
        else{
            _webView.scrollView.bounces = YES;
        }
        
        [self addSubview:_webView];
    }
    
    if (self.showProgressView) {
        if (!_progressView) {
            _progressView = [[UIProgressView alloc] init];
            _progressView.frame = CGRectMake(self.webViewRect.origin.x, CGRectGetMinY(self.webViewRect), CGRectGetWidth(self.webViewRect),2);
        }
        [self addSubview:_progressView];
        
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew| NSKeyValueObservingOptionOld context:nil];
    }
    else {
        _progressView = nil;
    }
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
     [self addWebview];
    NSLog(@"layoutSubviews");
}

- (void)addWebview {
    if (!_webView) {
        [self webViewInit];
    }
    NSLog(@"webViewInit");

    _webView.frame = self.webViewRect;
    _webView.scrollView.scrollEnabled = self.canScroll;
    NSLog(@"webViewInit_webViewRect%@",NSStringFromCGRect(self.webViewRect));

    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.htmlUrl]]];
    NSLog(@"webViewInit_htmlUrl%@",self.htmlUrl);
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    
    NSLog(@" %s,change = %@",__FUNCTION__,change);
    
    if ([keyPath isEqual: @"estimatedProgress"] && object == _webView) {
        [self.progressView setAlpha:1.0f];
        [self.progressView setProgress:_webView.estimatedProgress animated:YES];
        if(_webView.estimatedProgress >= 1.0f) {
            [UIView animateWithDuration:0.3 delay:0.3 options:UIViewAnimationOptionCurveEaseOut animations:^{
                [self.progressView setAlpha:0.0f];
            } completion:^(BOOL finished) {
                [self.progressView setProgress:0.0f animated:NO];
            }];
        }
    }
    else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


@end
